package com.timi_licai.timi_licai_account;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.timi_licai.timi_licai_account.adapter.BookBaseAdapter;
import com.timi_licai.timi_licai_account.adapter.CommonFragmentAdapter;
import com.timi_licai.timi_licai_account.database.DatabaseUtils;
import com.timi_licai.timi_licai_account.dialog.AddCountDialog;
import com.timi_licai.timi_licai_account.dialog.EditBookDialog;
import com.timi_licai.timi_licai_account.fragment.CircleBookFragment;
import com.timi_licai.timi_licai_account.fragment.KeyLineFragment;
import com.timi_licai.timi_licai_account.fragment.MainFragment;
import com.timi_licai.timi_licai_account.fragment.SettingFragment;
import com.timi_licai.timi_licai_account.listener.EditBookInterface;
import com.timi_licai.timi_licai_account.listener.KeyLineInterface;
import com.timi_licai.timi_licai_account.listener.MyCallback;
import com.timi_licai.timi_licai_account.model.AccountBook;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;


public class MainActivity extends FragmentActivity implements ViewPager.OnPageChangeListener,
        View.OnClickListener, MyCallback, KeyLineInterface, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    private ViewPager viewPager;
    private SlidingMenu slidingmenu;
    private KeyLineFragment keyLineFragment;
    private MainFragment mainFragment;
    private List<AccountBook> data;
    private BookBaseAdapter bookBaseAdapter;
    private CircleBookFragment circleBookFragment;
    private AccountBook book;

    /**
     * onCreate方法 在初始化的时候调用
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //测试数据库类
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        slidingmenu = (SlidingMenu) findViewById(R.id.slidingmenu);
        //SlidingMenu中添加账本的按钮

        //添加各个模块的Fragment
        List<Fragment> linkedList = new LinkedList<Fragment>();
        mainFragment = new MainFragment(this);
        circleBookFragment = new CircleBookFragment();
        SettingFragment settingFragment = new SettingFragment();
        keyLineFragment = new KeyLineFragment();
        linkedList.add(mainFragment);
        linkedList.add(circleBookFragment);
        linkedList.add(keyLineFragment);
        linkedList.add(settingFragment);
        //设置ViewPager的Adapter
        CommonFragmentAdapter adapter = new CommonFragmentAdapter(getSupportFragmentManager(), linkedList);
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(this);
        //设置当前选中项为0
        viewPager.setCurrentItem(0);
        //设置slidingMenu的滑动模式为全屏滑动
        slidingmenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        viewPager.setOnPageChangeListener(this);

        data = new ArrayList<>();
        data = queryAccountBookFromDB();

        //获取slidingmenu中的ListView
        ListView slidingListView = (ListView) findViewById(R.id.book_list);
        slidingListView.setOnItemClickListener(this);
        bookBaseAdapter = new BookBaseAdapter(this, data);
        slidingListView.setAdapter(bookBaseAdapter);
        slidingListView.setOnItemClickListener(this);
        slidingListView.setOnItemLongClickListener(this);
        ImageView imgPersonal = (ImageView) findViewById(R.id.personal_headimg);
        imgPersonal.setOnClickListener(this);
    }


    /**
     * 上一次点击Back按钮的事件
     */
    private long lastBackTime = 0;

    /**
     * 当前Activity显示的时候，点击屏幕上面返回键的事件处理方法
     */
    @Override
    public void onBackPressed() {
        //1. 获取当前的毫秒数
        long ct = System.currentTimeMillis();
        //2.和上一次点击返回键的时间进行比较，相差2秒就退出
        if (ct - lastBackTime <= 2000) {
            //TODO 结束程序  利用super.onBackPressed() 让Activity 自己处理返回键或者 finish() 结束。
            finish();
            //也可以通过System.exit(0) 这个方法，终止整个应用程序进程
            // 进程终止，类似 Service之类的组件将不在继续运行
        } else {
            lastBackTime = ct;
            if (viewPager.getCurrentItem() == 0) {
                Toast.makeText(this, "再次点击退出Timi", Toast.LENGTH_SHORT).show();
            } else {
                viewPager.setCurrentItem(0);
            }

        }

    }

    //ViewPager 的OnPageChangeListener 用于处理 滑动事件冲突
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        switch (position) {
            case 0:
                //当前页为第0页的时候设置slidingmenu滑动模式为全屏
                slidingmenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
                break;
            default:
                //除了0页其余页的slidingmenu的滑动模式为NONE，不滑动
                slidingmenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 显示SlidMenu 和登录的onClick事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.menu_btn:
                slidingmenu.toggle();
                break;
            case R.id.personal_headimg:
                Intent intent = new Intent(this, LoadActivity.class);
                startActivity(intent);
                break;
        }
    }


    //收到标识，弹出菜单
    @Override
    public void set(String s) {
        if ("startslidingmenu".equals(s)) {
            slidingmenu.toggle();
        }
    }

    @Override
    public void getKeyLineDate(Date date) {
        keyLineFragment.getDate(date);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //TODO 这里发送的 bookid 是不对的，有待更新
        if (position == 0) {
            //点击了的第一个位置的Item 选中的是添加账本的按钮
            AddCountDialog dialog = new AddCountDialog(this, R.style.addCountDialog);
            view = LayoutInflater.from(this).inflate(R.layout.dialog_add_account_book, null, false);
            dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            Window window = dialog.getWindow();
            window.setWindowAnimations(R.style.cameraDialogAnim);
            window.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            dialog.onWindowAttributesChanged(layoutParams);
            dialog.show();
        } else {
            //todo  点击了item 默认选中了账本
            int chooseId = data.get(position).getId();//得到选中的账本的id
            ContentValues values = new ContentValues();
            values.put("ismark", 1);
            //将选中的位置的对应的isMark的值变为1
            DatabaseUtils.update(MyConstants.TABLE_ACCOUNT_BOOK, values, "_id=?", new String[]{chooseId + ""});
            values = new ContentValues();
            values.put("ismark", 0);
            DatabaseUtils.update(MyConstants.TABLE_ACCOUNT_BOOK, values, "_id !=?", new String[]{chooseId + ""});
            slidingmenu.toggle();
            mainFragment.updateBookId(chooseId);
            List<AccountBook> bookList = queryAccountBookFromDB();
            data.clear();
            data.addAll(bookList);
            bookBaseAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 从数据库中查找所有的账本
     *
     * @return
     */
    private List<AccountBook> queryAccountBookFromDB() {
        List<AccountBook> bookList = new LinkedList<>();
        Cursor cursor = DatabaseUtils.query(MyConstants.TABLE_ACCOUNT_BOOK, null, null, null, "_id desc");
        AccountBook accountBook;
        if (cursor != null) {
            while (cursor.moveToNext()) {
                accountBook = new AccountBook();
                int id = cursor.getInt(cursor.getColumnIndex("_id"));
                String bookname = cursor.getString(cursor.getColumnIndex("bookname"));
                int bookcount = cursor.getInt(cursor.getColumnIndex("bookcount"));
                int isMark = cursor.getInt(cursor.getColumnIndex("ismark"));
                accountBook.setId(id);
                accountBook.setBookname(bookname);
                accountBook.setBookcount(bookcount);
                accountBook.setIsmark(isMark);
                bookList.add(accountBook);
            }
            cursor.close();
        }
        AccountBook book = new AccountBook();
        book.setId(-1);
        book.setBookname("添加账本");
        book.setIsmark(-1);
        bookList.add(0, book);
        return bookList;
    }


    /**
     * 添加账本 点击Dialog完成按钮的回调方法
     */
    public void flushCountBook() {
        List<AccountBook> bookList = queryAccountBookFromDB();
        data.clear();
        data.addAll(bookList);
        bookBaseAdapter.notifyDataSetChanged();
    }

    /**
     * SlidingMenu中ListView的长点击事件
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     * @return
     */
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        book = data.get(position);
        int bookId = book.getId();
        Log.d("++++", "长点击了" + position + "位置的账本，账本名称是" + book.getBookname() + "bookID是" + bookId);

        EditBookDialog bookDialog = new EditBookDialog(this,R.style.addCategoryDialog,bookId);
        bookDialog.setContentView(R.layout.dialog_updata_book);
        bookDialog.setBookListener(new EditBookInterface() {
            @Override
            public void editBookClick (String name) {
                book.setBookname(name);
            }
        });
        Window window = bookDialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        bookDialog.show();

        flushCountBook();

        return true;
    }
}
